#include <iostream>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>

using namespace std;

#define PATHNAME "." // 项目名
#define PROJID 0x29C         // 项目编号

const int gsize = 4096;
const mode_t mode = 0666;

//将十进制数转为十六进制数
string toHEX(int x)
{
    char buffer[64];
    snprintf(buffer, sizeof buffer, "0x%x", x);
    return buffer;
}


// 获取key
key_t getKey()
{
    key_t key = ftok(PATHNAME, PROJID);
    if (key == -1)
    {
        // 失败，终止进程
        cerr << "ftok fail!  "
             << "errno: " << errno << " | " << strerror(errno) << endl;
        exit(1);
    }

    return key;
}

// 共享内存助手
int shmHelper(key_t key, size_t size, int flags)
{
    int shmid = shmget(key, size, flags);
    if (shmid == -1)
    {
        // 失败，终止进程
        cerr << "shmget fail!  "
             << "errno: " << errno << " | " << strerror(errno) << endl;
        exit(2);
    }

    return shmid;
}

// 创建共享内存
int createShm(key_t key, size_t size)
{
    return shmHelper(key, size, IPC_CREAT | IPC_EXCL | mode);
}

// 获取共享内存
int getShm(key_t key, size_t size)
{
    return shmHelper(key, size, IPC_CREAT);
}